unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    btn1: TButton;
    procedure FormCreate(Sender: TObject);
    procedure btn1Click(Sender: TObject);
  private
    h: THandle;
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation {$R *.dfm}

type

  TCThread = class(TThread)
  public
    procedure Execute; override;
  end;

procedure TCThread.Execute;
var
  h: THandle;
begin
  h := CreateMutex(nil, false, 'teste');
  while not Terminated do
  begin
    WaitForSingleObject(h, INFINITE);
    ReleaseMutex(h);
    // sleep(1);
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  TCThread.Create(false);
  h := CreateMutex(nil, True, 'teste');
  btn1.Tag := 1;
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  btn1.Tag := Integer(not boolean(btn1.Tag));
  if boolean(btn1.Tag) then
    WaitForSingleObject(h, INFINITE)
  else
    ReleaseMutex(h)
end;

end.
